package com.gp.study.tomcat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import com.gp.study.tomcat.bean.GpServletRegistry;
import com.gp.study.tomcat.http.GpRequestHandler;

public class NettyTomcat {
	
	 GpServletRegistry servletRegistry;
	 int port;
					
	public NettyTomcat(int port) {
		this.port = port;
	}

	public void start() {
		init();
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			 ServerBootstrap server = new ServerBootstrap();
			 server.group(bossGroup,workerGroup)
			 		// 主线程处理类,看到这样的写法，底层就是用反射
			 		.channel(NioServerSocketChannel.class)
			 		.childHandler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch)
								throws Exception {
							ChannelPipeline pipeline = ch.pipeline();
							// 无锁化串行编程
							//Netty对HTTP协议的封装，顺序有要求
							// HttpResponseEncoder 编码器
							pipeline.addLast(new HttpResponseEncoder());
							// HttpRequestDecoder 解码器
							pipeline.addLast(new HttpRequestDecoder());
							// 业务逻辑处理
							pipeline.addLast(new GpRequestHandler());
							
						}
					})
			 		// 针对主线程的配置 分配线程最大数量 128
					.option(ChannelOption.SO_BACKLOG, 128)
					// 针对子线程的配置 保持长连接
					.childOption(ChannelOption.SO_KEEPALIVE, true);
			 
			 	// 启动服务器
				ChannelFuture f = server.bind(port).sync();
				System.out.println("GP Tomcat 已启动，监听的端口是：" + port);
			    f.channel().closeFuture().sync();
			 System.out.println("gptomcat is runing at port "+port);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			// 关闭线程池
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	private  void init() {
		 // 加载解析配置文件   暂时用properties文件代替
		 //注册 servlet 和   对应的处理类
		 servletRegistry = new GpServletRegistry();
	}

}
